package leetcode_bin_tree_test;

import bin_tree.TreeNode;
import sun.reflect.generics.tree.Tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 993. 二叉树的堂兄弟节点
 */
public class IsCousins {
//    public static boolean isCousins(TreeNode root, int x, int y) {
//        // 具有唯一值的二叉树的根节点 root
//        Deque<TreeNode> deque = new LinkedList<>(); // 需要存储null节点
//        deque.offer(root);
//        while (!deque.isEmpty()) {
//            int size = deque.size();
//            int count = 0; // 下一层出现想x,y的次数
//            for (int i = 0; i < size; i++) {
//                int num = 0;
//                TreeNode node = deque.poll();
//                if (node == null) {
//                    continue;
//                }
//                TreeNode left = node.left;
//                TreeNode right = node.right;
//                if (left != null && (left.val == x || left.val == y)) {
//                    num ++;
//                }
//                if (right != null && (right.val == x || right.val == y)) {
//                    num ++;
//                }
//                if (num == 2) {
//                    return false;
//                }
//                if (num == 1) {
//                    count ++;
//                }
//                deque.offer(left);
//                deque.offer(right);
//            }
//            if (count == 2) {
//                return true;
//            }
//        }
//        return false;
//    }

    // 递归法
    TreeNode xParent, yParent;
    boolean xFound, yFound;
    int xDepth, yDepth;
    int x, y;
    public boolean isCousins(TreeNode root, int x, int y) {
        this.x = x;
        this.y = y;
        return xParent != yParent && xFound && yFound && xDepth == yDepth;
    }

    public void dfs(TreeNode root, int depth, TreeNode parent) {
        if (root == null) {
            return;
        }
        if (root.val == x) {
            xDepth = depth;
            xParent = parent;
            xFound = true;
        } else if (root.val == y) {
            yDepth = depth;
            yParent = parent;
            yFound = true;
        }
        if (xFound && yFound) {
            return;
        }
        dfs(root.left, depth + 1, root);
        // 控制不再寻找
        if (xFound && yFound) {
            return;
        }
        dfs(root.left, depth + 1, root);
        // 后面没有了，不用再加控制
    }
}

class Main {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(4);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        System.out.println(new IsCousins().isCousins(root, 4, 3));
    }
}
